package logic

import (
	"UserSrv/global/model"
	"UserSrv/global/pkg"
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"time"

	"UserSrv/internal/svc"
	"UserSrv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCodeLogic {
	return &SmsCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}
func (l *SmsCodeLogic) SmsCode(in *user.SmsCodeRequest) (*user.SmsCodeResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("sms_code_phone:%s", in.Phone)
	ok := model.UserRDB.Exists(model.Ctx, key).Val()
	if ok != 1 {
		for i := 0; i < 4; i++ {
			model.UserRDB.LPush(model.Ctx, key, time.Now().String())
		}
		model.UserRDB.Expire(model.Ctx, key, 60*time.Second)
	}
	count, _ := model.UserRDB.LLen(model.Ctx, key).Result()
	if count == 1 {
		return nil, fmt.Errorf("一分钟内只能发送三条短信")
	}
	model.UserRDB.RPop(model.Ctx, key)
	code := fmt.Sprintf("%d", rand.Intn(900000)+100000)
	key = fmt.Sprintf("sms_code_phone:%s:code", in.Phone)
	model.UserRDB.Set(model.Ctx, key, code, 180*time.Second)
	var SmsCode pkg.SmsSeed = pkg.HuYi{
		Phone: in.Phone,
		Code:  code,
	}
	fmt.Println(SmsCode)
	set, _ := json.Marshal(SmsCode)
	rabbitmq := pkg.NewRabbitMQSimple("" +
		"SmsSeed")
	rabbitmq.PublishSimple(string(set))
	return &user.SmsCodeResponse{}, nil
}
